package org.duang.tags;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.duang.kit.ObjectKit;
import org.duang.kit.ToolsKit;
import org.duang.vtor.annotation.Vtor;

public class Datatable extends BodyTagSupport {

	private static final long serialVersionUID = 1L;
	
	private String style; 
	private String id;
	private String bean;
	private List<String> columnList;

	@Override
	public int doStartTag() throws JspException {
		try {
			if(ToolsKit.isEmpty(id)) throw new JspException("table id  is not null");
			if(ToolsKit.isEmpty(bean)) throw new JspException("entity bean  is not null");
			columnList = new ArrayList<String>();
			style = (ToolsKit.isEmpty(style)) ? "" : style;
			pageContext.getOut().write(buildHtml());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}

	@Override
	public int doAfterBody() throws JspException {
		return SKIP_BODY;
	}

	@SuppressWarnings("static-access")
	@Override
	public int doEndTag() throws JspException {
		return this.EVAL_PAGE;
	}
	
	private String buildHtml(){
		StringBuilder sb = new StringBuilder();
		String fieldString = getBeanFieldString();
		sb.append("<table id='"+ id +"' class='"+style+"'>");
		sb.append("<thead>").append(fieldString).append("</thead>");
		sb.append("<tfoot>").append(fieldString).append("</tfoot>");
		sb.append("</table>");
		String jsPath = "${ctx}" + id.substring(0, id.indexOf("_"))+".js";
		sb.append("<script type='text/javascript' charset='UTF-8' src='"+jsPath+"'></script>");
		return sb.toString();
	}

	private String getBeanFieldString() {
		StringBuilder fieldString = new StringBuilder("<tr>");
//		Object obj = ObjectKit.newInstance(bean);
//		Map<String, Field> map = ObjectKit.getFieldMap(obj)
//		for(Iterator<Entry<String,Field>> it = map.entrySet().iterator(); it.hasNext();){
//			Entry<String,Field> entry = it.next();
//			Field field = entry.getValue();
//			Vtor vtor = field.getAnnotation(Vtor.class);
//			if(ToolsKit.isNotEmpty(vtor)){
//				columnList.add(entry.getKey());
//				fieldString.append("<th>").append(vtor.desc()).append("</th>");
//			}
//		}
//		fieldString.append("</tr>");
		return fieldString.toString();
	}
	public String getStyle() {
		return style;
	}

	public void setStyle(String style) {
		this.style = style;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getBean() {
		return bean;
	}

	public void setBean(String bean) {
		this.bean = bean;
	}

	
}
